package view.components
{
	import flash.display.DisplayObject;
	import flash.events.Event;
	import flash.text.TextField;
	
	import global.Resource;
	
	import utils.DisplayTool;
	import utils.TextTool;

	public class ImgButton extends Button
	{
		private var _bg:DisplayObject;
		protected var _face:DisplayObject;
		private var _text:String;
		private var _textField:TextField;
		private var _fontSize:int;
		private var _fontColor:int;
		private var _bold:Boolean;
		
		public var param1:*;
		
		public function ImgButton(x:int, y:int, id:int, onClickFunction:Function,width:int,height:int,bg:String,face:String,text:String = null,fontSize:int= 12,fontColor:uint=0xFFFFFF,bold:Boolean=true)
		{
			super(x, y, id, onClickFunction);
			this.buttonMode = true;
			this.mouseChildren = false;
			_bold = bold;
			_fontSize = fontSize;
			_fontColor = fontColor;

			_bg = Resource.getShape(bg);
			if (_bg == null)
			{
				_bg = Resource.getImg(bg);
			}
			
			if (face)
			{
				_face = Resource.getImg(face);
			}
			
			
		
			_text = text;
			
			if (width != -1)
			{
				_bg.width = width;
			}	
			
			if (height != -1)
			{
				_bg.height = height;
			}
			
			initAll();
			
			if (_face is TempBitmap)
			{
				_face.addEventListener(Event.COMPLETE,onFaceComplete);
			}
		}
		
		private function onFaceComplete(event:Event):void
		{
			event.target.removeEventListener(Event.COMPLETE,onFaceComplete);
			setFace(_face);
			setFace(_textField);
		}
		
		
		private function initAll():void
		{
			addChild(_bg);
			if (_face != null)
			{
				setFace(_face);
				addChild(_face);
			}
			else if (_text != null)
			{
				_textField = TextTool.getTextField(width,20,_fontSize,_fontColor,false,_bold,"center");
				
				if (_text == "坐下")
				{
					trace(width);
				}
				
				_textField.text = _text;
				
				addChild(_textField);
				setFace(_textField);
			}
			
		}
		
		public function resetFace(imgKey:String):void
		{
			DisplayTool.removeChild(_face.parent,_face);
			if (imgKey)
			{
				_face = Resource.getImg(imgKey);
			}
			if (_face != null)
			{
				setFace(_face);
				addChild(_face);
			}
		}
		
		private function setFace(obj:DisplayObject):void
		{
			if (obj)
			{
				obj.x = (_bg.width - obj.width) * .5;
				obj.y = (_bg.height - obj.height) * .5;
			}
		}
		
		override public function destroy():void
		{
			super.destroy();
			DisplayTool.removeAllChild(this);
			_bg = null;
			_face = null;
			_textField = null;
		}
	}
}